﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.WebPages;
using System.Web;
using System.IO;

namespace MTO.Framework.Web.Mvc.Helpers
{
    public class Analytics : HelperPage
    {
        /// <summary>
        /// Sert à générer le code javascript requis pour utiliser Piwik Analytics
        /// </summary>
        /// <param name="serverHost">L'adresse URL pour rejoindre le site de Piwik</param>
        /// <param name="siteId">L'id de votre site qui est enregistré avec Piwik</param>
        /// <returns></returns>
        public static HelperResult GetPiwikHtml(Uri serverHost, int siteId)
        {
            string host = serverHost.Host;

            return new HelperResult(x =>
            {
                HelperPage.WriteLiteralTo(x, "    <!-- Piwik -->\r\n");
                HelperPage.WriteLiteralTo(x, "    <script type=\"text/javascript\">\r\n        var pkBaseURL = ((\"https:\" == document.location.protocol) ? \"https://" + host + "/\" : \"http://" + host + "/\");\r\n        document.write(unescape(\"%3Cscript src='\" + pkBaseURL + \"piwik.js' type='text/javascript'%3E%3C/script%3E\"));\r\n    </script>\r\n");
                HelperPage.WriteLiteralTo(x, "    <script type=\"text/javascript\">\r\n        try{\r\n            var piwikTracker = Piwik.getTracker(pkBaseURL + \"piwik.php\", ");
                HelperPage.WriteTo(x, siteId);
                HelperPage.WriteLiteralTo(x, ");\r\n            piwikTracker.trackPageView();\r\n            piwikTracker.enableLinkTracking();\r\n        } catch(err) {}\r\n    </script>\r\n");
                HelperPage.WriteLiteralTo(x, "    <noscript><p><img src=\"http://" + host + "/piwik.php?idsite=" + siteId + "\" style=\"border:0\" alt=\"\" /></p></noscript>\r\n");
                HelperPage.WriteLiteralTo(x, "    <!-- End Piwik Tracking Code -->");
            });
        }
    }
}
